<template>
    <div class="teacher-leave-approval">
        <div class="breadcrumb">
            <span>考勤管理</span> &gt; <span>教师考勤</span> &gt; <span>请假审批</span>
        </div>

        <div class="tabs">
            <div class="tab-item" @click="navigateTo('/main/teacher-attendance/manage')">我的请假</div>
            <div class="tab-item active">请假审批</div>
            <div class="tab-item" @click="navigateTo('/main/teacher-attendance/statistics')">考勤统计</div>
            <div class="tab-item" @click="navigateTo('/main/teacher-attendance/time-setting')">考勤时间设置</div>
        </div>

        <div class="filter-bar">
            <el-date-picker v-model="applyTime" type="date" placeholder="申请时间" class="filter-item" />

            <el-date-picker v-model="leaveTime" type="date" placeholder="请假时间" class="filter-item" />

            <el-select v-model="leaveType" placeholder="请假类型" class="filter-item">
                <el-option label="事假" value="事假" />
                <el-option label="病假" value="病假" />
                <el-option label="公假" value="公假" />
            </el-select>

            <el-select v-model="approvalStatus" placeholder="审批状态" class="filter-item">
                <el-option label="待审批" value="待审批" />
                <el-option label="审批通过" value="审批通过" />
                <el-option label="审批驳回" value="审批驳回" />
            </el-select>

            <el-button type="primary" @click="handleSearch" class="search-btn">查 询</el-button>
            <el-button @click="handleReset" class="reset-btn">重 置</el-button>
        </div>

        <div class="result-info">查询结果：共计 {{ leaveData.length }} 条数据</div>

        <el-table :data="leaveData" border style="width: 100%" v-loading="loading">
            <el-table-column prop="department" label="部门" min-width="100" />
            <el-table-column prop="teacherName" label="姓名" min-width="100" />
            <el-table-column prop="startTime" label="开始时间" min-width="160" />
            <el-table-column prop="endTime" label="结束时间" min-width="160" />
            <el-table-column prop="leaveType" label="请假类型" min-width="100" />
            <el-table-column prop="applyTime" label="申请时间" min-width="160" />
            <el-table-column prop="status" label="审批状态" min-width="120">
                <template #default="scope">
                    <el-tag :type="scope.row.status === '待审批' ? 'warning' :
                        scope.row.status === '审批通过' ? 'success' : 'danger'">
                        {{ scope.row.status }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" min-width="120" fixed="right">
                <template #default="scope">
                    <el-button type="primary" size="small" v-if="scope.row.status === '待审批'"
                        @click="approveLeave(scope.row)" class="approval-btn">
                        立即审批
                    </el-button>
                    <el-button type="info" size="small" v-else @click="viewLeaveDetail(scope.row)">
                        查看详情
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 审批对话框 -->
        <el-dialog v-model="approvalDialogVisible" title="请假审批" width="500px">
            <div class="approval-form">
                <div class="approval-detail">
                    <div class="detail-item">
                        <span class="label">部门：</span>
                        <span class="value">{{ currentLeave.department }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">姓名：</span>
                        <span class="value">{{ currentLeave.teacherName }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">请假类型：</span>
                        <span class="value">{{ currentLeave.leaveType }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">开始时间：</span>
                        <span class="value">{{ currentLeave.startTime }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">结束时间：</span>
                        <span class="value">{{ currentLeave.endTime }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">申请时间：</span>
                        <span class="value">{{ currentLeave.applyTime }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">请假理由：</span>
                        <span class="value">{{ currentLeave.reason }}</span>
                    </div>
                </div>

                <div class="approval-actions">
                    <el-button @click="approvalDialogVisible = false">取消</el-button>
                    <el-button type="danger" @click="rejectLeave">驳回</el-button>
                    <el-button type="success" @click="confirmApprove">通过</el-button>
                </div>
            </div>
        </el-dialog>

        <!-- 驳回对话框 -->
        <el-dialog v-model="rejectDialogVisible" title="驳回原因" width="500px">
            <el-form :model="rejectForm" ref="rejectFormRef" :rules="rejectRules">
                <el-form-item label="驳回原因" prop="reason">
                    <el-input v-model="rejectForm.reason" type="textarea" :rows="4" placeholder="请输入驳回原因" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="rejectDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmReject" :loading="submitting">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 查看详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="请假详情" width="500px">
            <el-descriptions :column="1" border>
                <el-descriptions-item label="部门">{{ currentLeave.department }}</el-descriptions-item>
                <el-descriptions-item label="姓名">{{ currentLeave.teacherName }}</el-descriptions-item>
                <el-descriptions-item label="请假类型">{{ currentLeave.leaveType }}</el-descriptions-item>
                <el-descriptions-item label="开始时间">{{ currentLeave.startTime }}</el-descriptions-item>
                <el-descriptions-item label="结束时间">{{ currentLeave.endTime }}</el-descriptions-item>
                <el-descriptions-item label="申请时间">{{ currentLeave.applyTime }}</el-descriptions-item>
                <el-descriptions-item label="请假理由">{{ currentLeave.reason }}</el-descriptions-item>
                <el-descriptions-item label="审批状态">
                    <el-tag :type="currentLeave.status === '待审批' ? 'warning' :
                        currentLeave.status === '审批通过' ? 'success' : 'danger'">
                        {{ currentLeave.status }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item v-if="currentLeave.approver" label="审批人">
                    {{ currentLeave.approver }}
                </el-descriptions-item>
                <el-descriptions-item v-if="currentLeave.approvalTime" label="审批时间">
                    {{ currentLeave.approvalTime }}
                </el-descriptions-item>
                <el-descriptions-item v-if="currentLeave.rejectReason" label="驳回理由">
                    {{ currentLeave.rejectReason }}
                </el-descriptions-item>
            </el-descriptions>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="detailDialogVisible = false">关闭</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { getTeacherLeaveList, approveTeacherLeave } from '@/api/teacherKaoqin'

const router = useRouter()
const loading = ref(false)
const submitting = ref(false)

// 当前审批人信息（实际项目中应从用户登录信息获取）
const currentApprover = {
    name: '张主任',
    role: '主任'
}

// 查询条件
const applyTime = ref<Date | null>(null)
const leaveTime = ref<Date | null>(null)
const leaveType = ref('')
const approvalStatus = ref('待审批')

// 请假数据
const leaveData = ref<any[]>([])

// 审批相关
const approvalDialogVisible = ref(false)
const rejectDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const rejectFormRef = ref<FormInstance>()
const currentLeave = ref({
    id: '',
    department: '',
    teacherName: '',
    startTime: '',
    endTime: '',
    leaveType: '',
    reason: '',
    applyTime: '',
    status: '',
    approver: '',
    approvalTime: '',
    rejectReason: ''
})

const rejectForm = ref({
    reason: ''
})

const rejectRules = {
    reason: [{ required: true, message: '请输入驳回原因', trigger: 'blur' }]
}

// 日期格式化工具函数
function formatDate(date: Date | string): string {
    if (!date) return ''

    if (typeof date === 'string') {
        return date
    }

    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')

    return `${year}-${month}-${day}`
}

// 查询
async function handleSearch() {
    loading.value = true
    try {
        const params: any = {}

        if (leaveType.value) {
            params.leaveType = leaveType.value
        }

        if (approvalStatus.value) {
            params.status = approvalStatus.value
        }

        if (applyTime.value) {
            params.applyDate = formatDate(applyTime.value)
        }

        if (leaveTime.value) {
            params.leaveDate = formatDate(leaveTime.value)
        }

        const response: any = await getTeacherLeaveList(params)
        if (response.data && response.data.code === 200) {
            leaveData.value = response.data.data

            // 如果是第一次加载且未指定状态，自动筛选待审批的请假申请
            if (approvalStatus.value === '待审批') {
                ElMessage.info(`待审批的请假申请: ${leaveData.value.filter(item => item.status === '待审批').length} 条`)
            }
        }
    } catch (error) {
        console.error('获取请假数据失败:', error)
        ElMessage.error('获取请假数据失败')
    } finally {
        loading.value = false
    }
}

// 重置
function handleReset() {
    applyTime.value = null
    leaveTime.value = null
    leaveType.value = ''
    approvalStatus.value = '待审批'
    handleSearch()
}

// 查看详情
function viewLeaveDetail(row: any) {
    currentLeave.value = { ...row }
    detailDialogVisible.value = true
}

// 审批请假
function approveLeave(row: any) {
    currentLeave.value = { ...row }
    approvalDialogVisible.value = true
}

// 确认通过
function confirmApprove() {
    ElMessageBox.confirm('确定要通过此请假申请吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
    }).then(() => {
        submitting.value = true

        // 实际应调用API
        const params = {
            id: currentLeave.value.id,
            status: '审批通过',
            approver: currentApprover.name,
            approvalTime: formatDate(new Date())
        }

        approveTeacherLeave(currentLeave.value.id, params)
            .then((response: any) => {
                if (response.data && response.data.code === 200) {
                    ElMessage.success(response.data.message || '审批通过成功')
                    handleSearch() // 刷新数据以显示最新状态
                } else {
                    ElMessage.error(response.data?.message || '操作失败')
                }
            })
            .catch(error => {
                console.error('审批失败:', error)
                ElMessage.error('审批失败')
            })
            .finally(() => {
                approvalDialogVisible.value = false
                submitting.value = false
            })
    }).catch(() => { })
}

// 驳回请假
function rejectLeave() {
    rejectForm.value.reason = ''
    approvalDialogVisible.value = false
    rejectDialogVisible.value = true
}

// 确认驳回
function confirmReject() {
    rejectFormRef.value?.validate((valid) => {
        if (!valid) return

        submitting.value = true

        // 实际应调用API
        const params = {
            id: currentLeave.value.id,
            status: '审批驳回',
            approver: currentApprover.name,
            approvalTime: formatDate(new Date()),
            rejectReason: rejectForm.value.reason
        }

        approveTeacherLeave(currentLeave.value.id, params)
            .then((response: any) => {
                if (response.data && response.data.code === 200) {
                    ElMessage.success(response.data.message || '已驳回请假申请')
                    handleSearch() // 刷新数据以显示最新状态
                } else {
                    ElMessage.error(response.data?.message || '操作失败')
                }
            })
            .catch(error => {
                console.error('驳回失败:', error)
                ElMessage.error('驳回失败')
            })
            .finally(() => {
                rejectDialogVisible.value = false
                submitting.value = false
            })
    })
}

// 导航到指定路由
function navigateTo(route: string) {
    router.push(route)
}

// 组件挂载时获取数据
onMounted(() => {
    handleSearch()
})
</script>

<style scoped>
.teacher-leave-approval {
    padding: 0 20px;
}

.breadcrumb {
    display: flex;
    align-items: center;
    height: 50px;
    font-size: 14px;
    color: #606266;
}

.tabs {
    display: flex;
    border-bottom: 1px solid #e4e7ed;
    margin-bottom: 20px;
}

.tab-item {
    padding: 12px 20px;
    font-size: 14px;
    cursor: pointer;
    color: #606266;
    border-bottom: 2px solid transparent;
}

.tab-item.active {
    color: #409EFF;
    border-bottom: 2px solid #409EFF;
}

.filter-bar {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 20px;
    align-items: center;
}

.filter-item {
    width: 180px;
}

.search-btn,
.reset-btn {
    margin-left: 10px;
}

.result-info {
    background-color: #ecf8ff;
    padding: 10px;
    margin-bottom: 10px;
    border-radius: 4px;
    color: #409EFF;
}

.approval-form {
    padding: 10px;
}

.approval-detail {
    margin-bottom: 20px;
}

.detail-item {
    display: flex;
    margin-bottom: 10px;
}

.detail-item .label {
    width: 100px;
    color: #606266;
    text-align: right;
    padding-right: 12px;
}

.detail-item .value {
    flex: 1;
    color: #303133;
}

.approval-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style>